﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml.Linq;
using System.Xml;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace laicigoujiaoyi
{
    public partial class GetCookie : Form
    {
        public GetCookie()
        {
            InitializeComponent();
        }
        static string papa = Application.StartupPath;
        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Url = new Uri("https://passport.baidu.com/");

        }
        private static string GetCookies(string url)
        {
            uint datasize = 256;
            StringBuilder cookieData = new StringBuilder((int)datasize);
            if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero))
            {
                if (datasize < 0)
                    return null;

                cookieData = new StringBuilder((int)datasize);
                if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero))
                    return null;
            }
            return cookieData.ToString();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            CookieContainer myCookieContainer = new CookieContainer();
            if (webBrowser1.Document.Cookie != null)
            {

                string cookieStr = webBrowser1.Document.Cookie;
                string[] cookstr = cookieStr.Split(';');
                foreach (string str in cookstr)
                {
                    string[] cookieNameValue = str.Split('=');
                    Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                    ck.Domain = "www.baidu.com";
                    myCookieContainer.Add(ck);
                }
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            CookieContainer cookieContainer = new CookieContainer();

            //得到cookie
            CookieCollection cookies = cookieContainer.GetCookies(new Uri("http://baidu.com"));
            //遍历得到cookie
            if (cookies != null)
            {
                foreach (System.Net.Cookie cookie in cookies)
                {
                    //每一个cookie
                }
            }

            //得到cookie的头
            string cookieHeader = cookieContainer.GetCookieHeader(new Uri("http://baidu.com"));
        }
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int InternetSetCookieEx(string lpszURL, string lpszCookieName, string lpszCookieData, int dwFlags, IntPtr dwReserved);

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                // var cookieString = GetCookies("https://passport.baidu.com");
                //CookieContainer myCookieContainer = new CookieContainer();
                string cookieStr = GetCookies("https://passport.baidu.com");
                string[] cookstr = cookieStr.Split(';');
                Dictionary<string, string> strlist = new Dictionary<string, string>();
                foreach (string str in cookstr)
                {
                    string[] cookieNameValue = str.Split('=');
                    //  Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                    strlist.Add(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                    ///   ck.Domain = "www.baidu.com";
                    /// myCookieContainer.Add(ck);
                }
                string BDUSS = strlist["BDUSS"];
                Dog.GetCookieva = BDUSS;
                string ret = Dog.showUser();
                JObject res_j = (JObject)JsonConvert.DeserializeObject(ret);
                string u_name = (string)res_j["data"]["userName"];
                string u_amount = (string)res_j["data"]["amount"];
                u_name= "齐卓" + u_name;
                u_name = u_name.Replace("*", "0");

                if (true)
                {

                }
                bool numxml = false;
                //获取根节点对象
                XmlDocument xmlDoc = new XmlDocument();
                if (File.Exists(papa + "\\Cookie.xml"))
                {
                    xmlDoc.Load(papa + "\\Cookie.xml");//加载xml文件，文件
                    XmlNode xns = xmlDoc.SelectSingleNode("Cookie");//查找要修改的节点
                    XmlNodeList xnl = xns.ChildNodes;//取出所有的子节点
                    foreach (XmlNode xn in xnl)
                    {
                        XmlElement xe = (XmlElement)xn;//将节点转换一下类型
                        if (xe.Name == u_name.ToString ())//判断该子节点是否是要查找的节点
                        {
                            numxml = true;
                            xe.InnerText = BDUSS.ToString ();//设置新值
                            xmlDoc.Save(papa + "\\Cookie.xml");
                            MessageBox.Show("修改成功");

                        }
                    }

                    if (!numxml)
                    {
                        XmlNode root = xmlDoc.SelectSingleNode("Cookie");
                        XmlElement xe = xmlDoc.CreateElement(u_name.ToString ());
                        xe.InnerText = BDUSS;
                        root.AppendChild(xe);
                        xmlDoc.Save(papa + "\\Cookie.xml");
                        MessageBox.Show("获取成功");
                    }


                }
                else
                {
                    XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
                    xmlDoc.AppendChild(node);
                    //创建根节点 
                    XmlNode root1 = xmlDoc.CreateElement("Cookie");
                    XmlElement xe = xmlDoc.CreateElement(u_name);
                    xe.InnerText = BDUSS;
                    //  xe.SetAttribute("BDUSS", BDUSS);

                    root1.AppendChild(xe);
                    xmlDoc.AppendChild(root1);
                    xmlDoc.Save(papa + "\\Cookie.xml");
                    MessageBox.Show("创建成功");
                }

            }
            catch (Exception)
            {


            }
        }

        private void GetCookie_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(papa);//加载xml文件，xmlpath 为XML文件的路径
                              //查找要修改的节点，从根节点开始，否则会报错
            XmlNode xns = xmlDoc.SelectSingleNode("Cookie");
            XmlNodeList xnl = xns.ChildNodes;//取出所有的子节点
                                             //遍历子节点
            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;
                //将节点转换一下类型 
                //判断该子节点是否是要查找的节点 (通过节点属性值，查找指定节点)
                //if (xe.GetAttribute("ID") == "ID")
                //{
                //    XmlNodeList xnl2 = xe.ChildNodes;//取出该子节点下面的所有元素
                //    foreach (XmlNode xn2 in xnl2)
                //    {
                //        XmlElement xe2 = (XmlElement)xn2;//转换类型
                //        if (xe2.Name == "childname")//最小节点，通过名称查找定位节点
                //        {
                //            xe2.InnerText = "节点值";//直接修改节点的值
                //        }
                //    }
                //    //如果需要遍历多次，则不用break；
                //    break;//如果更新完了指定节点，有需要则退出循环
                //}
            }
            xmlDoc.Save(papa);//保存的该XML文件,否则更新无效
        }
    }

}
